/*
 *
 *  AutoWallpaper (Android) Version 1.x
 *  Copyright (C) 2010 - 2011, Tyler H. Jones (me@tylerjones.me)
 *  http://www.autowallpaper.org/
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */

package com.tylerhjones.autowallpaper;

import java.io.File;
import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;
import com.tylerhjones.autowallpaper.AWService;

///*****************************************************************************************//
///*** AutoWallpaperActivity class                                                       ***//
///*****************************************************************************************//

public class AutoWallpaperActivity extends Activity {

///*****************************************************************************************//
///*** Variable declarations                                                             ***//
///*****************************************************************************************//			
	private final String TAG = "AWActivity";
	private AWService AWS;
	
	private ArrayList<String> IntervalIndexList = new ArrayList<String>();
	private ArrayList<String> WPModeList = new ArrayList<String>();
	
	private CheckBox chkActive;
	private CheckBox chkStartup;
	private CheckBox chkRandom;
	
	private Spinner cboIntervals;	
	private Spinner cboDisplayOptions;
	public Uri imageUri = null;
	public Uri imgManagerUri = null;
	public TextView lblNumImagesLoaded;
	
	private static final int DIALOG_ADDALLDIRS_ID = 1;
	private static final int DIALOG_ABOUT_ID = 2;
	private static final int DIALOG_BETAWARN_ID = 3;
	private static final int DIALOG_WELCOME_ID = 4;
	
	private AWCore Core;

///*****************************************************************************************//
///*** onCreate function, beginning of AutoWallpaperActivity                             ***//
///*****************************************************************************************//
	   
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Log.d(TAG, "onCreate: Beginning...");
        Core = new AWCore(this);
        Log.d(TAG, "onCreate: Bind service");
        doBindService();   
        lblNumImagesLoaded = (TextView) findViewById(R.id.lblNumImagesLoaded);
        
        IntervalIndexList.add("1"); IntervalIndexList.add("2"); IntervalIndexList.add("6"); IntervalIndexList.add("12"); IntervalIndexList.add("24"); 
        IntervalIndexList.add("48"); IntervalIndexList.add("72"); IntervalIndexList.add("96"); IntervalIndexList.add("144"); IntervalIndexList.add("288"); 
        IntervalIndexList.add("9999"); IntervalIndexList.add("10000");
        WPModeList.add("center"); WPModeList.add("fit_xy"); WPModeList.add("scale_y"); WPModeList.add("scale_x"); WPModeList.add("scale_xy"); 
        Log.d(TAG, "onCreate: List items set");
        //sVal = getSharedPreferences(Common.SETTINGS, 0);
		//sEdit = sVal.edit();
		
        //Setup Spinners ----------------------------------------------------------------------
        cboIntervals = (Spinner) findViewById(R.id.cboIntervals);
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.intervals, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        cboIntervals.setAdapter(adapter);
        cboIntervals.setOnItemSelectedListener(new MyOnItemSelectedListener());
       
        cboDisplayOptions = (Spinner) findViewById(R.id.cboDisplayOptions);
        ArrayAdapter<CharSequence> optadapter = ArrayAdapter.createFromResource(this, R.array.wpoptions, android.R.layout.simple_spinner_item);
        optadapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        cboDisplayOptions.setAdapter(optadapter);
        cboDisplayOptions.setOnItemSelectedListener(new WPOptionsItemSelectedListener());
        Log.d(TAG, "onCreate: Combo boxes set");
        //Setup buttons --------------------------------------------------------------------------
        Button btnViewImages = (Button) findViewById(R.id.btnViewImages);
        btnViewImages.setOnClickListener(new View.OnClickListener() {
        	public void onClick(View view) {
        		OpenImageManager();
        	}
        });
        
        Button btnChangeWallpaper = (Button) findViewById(R.id.btnChangeWallpaper);
        btnChangeWallpaper.setOnClickListener(new View.OnClickListener() {
        	public void onClick(View view) {
        		ChangeWallpaper();
        	}
        });
        Log.d(TAG, "onCreate: Buttons set");
        
        //Setup CheckBoxes -----------------------------------------------------------------
        chkActive = (CheckBox) findViewById(R.id.chkActive);
        chkActive.setOnClickListener(new OnClickListener() {
        	@Override
        	public void onClick(View v) {
        		AWS.setTimer(Core.getTimerInterval(), ((CheckBox) v).isChecked());
        	}
        });        
        
        chkStartup = (CheckBox) findViewById(R.id.chkStrartup);
        chkStartup.setOnClickListener(new OnClickListener() {
        	@Override
        	public void onClick(View v) {
        		Core.setRunAtStartup(((CheckBox) v).isChecked());
        	}
        });  
        
        chkRandom = (CheckBox) findViewById(R.id.chkRandom);
        chkRandom.setOnClickListener(new OnClickListener() {
        	@Override
        	public void onClick(View v) {
        		Core.setRandom(((CheckBox) v).isChecked());
        	}
        });  
        
        
    }
    
    @Override
    public void onStart() {
    	super.onStart();
    	
        cboIntervals.setSelection(IntervalIndexList.indexOf(Integer.toString(Core.getTimerInterval())));
        cboDisplayOptions.setSelection(WPModeList.indexOf(Core.getWPMode()));
    	Log.d(TAG, "Spinners set...");
        chkActive.setChecked(Core.getAutoChange());
        chkStartup.setChecked(Core.getRunAtStartup());
        chkRandom.setChecked(Core.getRandom());
        lblNumImagesLoaded.setText("Total Available Images: " + String.valueOf(Core.getNumImages()));
        
    	if(Core.getFirstRun()) {
    		showDialog(DIALOG_WELCOME_ID);
    		Core.setFirstRun(false);
        }
    }
    
    @Override
    public void onDestroy() {
    	super.onDestroy();
    	doUnbindService();
    }
    
    @Override
    public void onResume() {
    	super.onResume();
    	lblNumImagesLoaded.setText("Total Available Images: " + String.valueOf(Core.getNumImages()));
    }
        
    void OpenImageManager() {
    	Intent intent = new Intent(this, ImageManager.class);
    	startActivity(intent);
    }
    
    private void ChangeWallpaper() {
    	AWS.NextWallpaper();
    }
    
///*****************************************************************************************//
///*** Show dialog/msgbox functions                                                      ***//
///*****************************************************************************************//
   
    private void ShowAbout() {
    	showDialog(DIALOG_ABOUT_ID);
    }
    
    private void ShowWebsite() {
    	Uri uri = Uri.parse( "http://" + getText(R.string.autowallpaper_site) );
		startActivity( new Intent( Intent.ACTION_VIEW, uri ) );
    }
    
    private void ShowDonate() {
    	Uri uri = Uri.parse( "http://" + getText(R.string.autowallpaper_donate_site) );
		startActivity( new Intent( Intent.ACTION_VIEW, uri ) );
    }
     
    protected Dialog onCreateDialog(int id) {
        Dialog adialog = null;
        switch(id) {
        case DIALOG_ADDALLDIRS_ID:
        	AlertDialog.Builder builder = new AlertDialog.Builder(this);
        	builder.setMessage(getText(R.string.addfileorfolder_msg_body))
        		   .setTitle(getText(R.string.addfileorfolder_msg_title))
        	       .setCancelable(false)
        	       .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
        	    	   @Override
        	           public void onClick(DialogInterface dialog, int id) {
        	               lblNumImagesLoaded.setText("Current Dir:" + imageUri.getPath());
        	           }
        	       })
        	       .setNegativeButton("No", new DialogInterface.OnClickListener() {
        	    	   @Override
        	           public void onClick(DialogInterface dialog, int id) {
        	                dialog.cancel();
        	           }
        	       });
        	AlertDialog alert = builder.create();
        	adialog = alert;
            break;
        case DIALOG_ABOUT_ID:
        	adialog = new AlertDialog.Builder(this)
            .setTitle(getText(R.string.about_msg_title))
            .setMessage(getText(R.string.about_msg_body))
            .setPositiveButton("Close", new DialogInterface.OnClickListener() {
            	@Override
                public void onClick(DialogInterface iface, int num) { 
            		iface.cancel();
                }
             }).create();
            break;
        case DIALOG_BETAWARN_ID:
        	adialog = new AlertDialog.Builder(this)
            .setTitle(getText(R.string.beta_msg_title))
            .setMessage(getText(R.string.beta_msg_body))
            .setPositiveButton("Close", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface iface, int num) { 
                }
                })
            .setNegativeButton("Exit", new DialogInterface.OnClickListener() {
            	@Override
                public void onClick(DialogInterface iface, int num) { 
            		AutoWallpaperActivity.this.stopService(new Intent(getApplicationContext(), AWService.class));
                	AutoWallpaperActivity.this.finish();
                }
                }).create();
            break;
            
        case DIALOG_WELCOME_ID:
    		final Dialog ddialog = new Dialog(this);
    		adialog = ddialog;
            ddialog.setContentView(R.layout.welcome_dialog);
            ddialog.setTitle(getText(R.string.welcome_title));
            ddialog.setCancelable(true);
            //Setup textview
            TextView txtWelcome = (TextView) ddialog.findViewById(R.id.txtWelcome);
            txtWelcome.setText(getText(R.string.welcome_msg));

            //Setup buttons
            Button btnWelcomeClose = (Button) ddialog.findViewById(R.id.btnWelcomeClose);
            btnWelcomeClose.setOnClickListener(new OnClickListener() {
            @Override
                public void onClick(View v) {
            		ddialog.dismiss();
                }
            });
            ddialog.show();
            break;
        default:
            adialog = null;
            break;
        }
        return adialog;
    }
    
///*****************************************************************************************//
///*** Event handler functions                                                           ***//
///*****************************************************************************************//
    
    public class MyOnItemSelectedListener implements OnItemSelectedListener {

        public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
        	//Toast.makeText(parent.getContext(), "Interval set to " + parent.getItemAtPosition(pos).toString(), Toast.LENGTH_LONG).show();
        	AWS.setTimer(Integer.valueOf(IntervalIndexList.get(pos)), Core.getAutoChange());
        }

		@Override
		public void onNothingSelected(AdapterView<?> arg0) {
			// TODO Auto-generated method stub
		}
    }

    public class WPOptionsItemSelectedListener implements OnItemSelectedListener {

        public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
        	//Toast.makeText(parent.getContext(), "Display option set to: " + parent.getItemAtPosition(pos).toString(), Toast.LENGTH_LONG).show();
        	Core.setWPMode(WPModeList.get(pos));
        	Log.v("WPMode Value", Core.getWPMode());
        }

		@Override
		public void onNothingSelected(AdapterView<?> arg0) {
			// TODO Auto-generated method stub
			
		}
    }
    
    public boolean onCreateOptionsMenu(Menu menu)
    {
    	super.onCreateOptionsMenu(menu);
    	MenuInflater inflater = getMenuInflater();
    	inflater.inflate(R.menu.main_menu, menu);
    	return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
        case R.id.mnuMainExit:
            this.stopService(new Intent(getApplicationContext(), AWService.class));
            this.finish();
            return true;
        case R.id.mnuMainAbout:
            ShowAbout();
            return true;
        case R.id.mnuMainHelp:
            showDialog(DIALOG_WELCOME_ID);
            return true;
        case R.id.mnuMainWebsite:
            ShowWebsite();
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }
    
    @Override
    protected void onActivityResult(final int requestCode, int resultCode, final Intent data) { 	
    	if(resultCode == Activity.RESULT_OK) {
    		switch(requestCode) {
    			case Common.MEDIA_IMAGE_REQUEST_CODE:
    				imageUri = data.getData();
    				Log.d("onActivityResult", "imgsrc: " + imageUri.getPath() + "  --  imgfile: " + imageUri.toString());
    				showDialog(DIALOG_ADDALLDIRS_ID);
    	 			break;

    			case Common.IMAGE_MANAGER_REQUEST_CODE:
    				imgManagerUri = data.getData();
    				Log.d("onActivityResult", "imgsrc: " + imgManagerUri.getPath() + "  --  ReturnCmd: " + imgManagerUri.toString());
    				showDialog(DIALOG_ADDALLDIRS_ID);
    	 			break;    	 		

    	 		default:
    	 			Log.w("onActivityResult", "An activity finished and it wasn't recognized by the select-case statement.");
    	 			break;
    		}
    	}
    }
        
///*****************************************************************************************//
///*** Service binding/connection handling                                               ***//
///*****************************************************************************************//
       
    private ServiceConnection svcConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className, IBinder service) {
        	try {
	        	Log.d("onServiceConnected", "Service is being started...");
	        	AWS = ((AWService.LocalBinder)service).getService();
	        	Log.d("onServiceConnected", "AWS object value set..");
	            //Toast.makeText(AutoWallpaperActivity.this, getText(R.string.service_conn_notif), Toast.LENGTH_SHORT).show();
	            Log.d("onServiceConnected", "Service startup complete.");
	            
	            //Check if this version is beta. Warn the user if it is.
	            if(getText(R.string.versionnum).toString().toUpperCase().contains("BETA")) { showDialog(DIALOG_BETAWARN_ID); }
    		} catch (Exception e) {
    		    Log.e("onServiceConnected", "Error in onServiceConnected", e);
    		}
        }
        
        public void onServiceDisconnected(ComponentName className) {
        	AWS = null;
          	Log.w("AutoWallpaperActivity", "Service was disconnected! Might be intentional, might not be...");
            Toast.makeText(getApplicationContext(), getText(R.string.service_disconn_notif), Toast.LENGTH_SHORT).show();
        }
    };

    void doBindService() {
    	Thread t = new Thread(){
    		public void run(){
            	Log.d("doBindService", "Binding thread started...");
    			boolean res = bindService(new Intent(getApplicationContext(), AWService.class), svcConnection, Context.BIND_AUTO_CREATE);
    			String str;
    			if(res) { str = "TRUE"; } else { str = "FALSE"; }
    			Log.d("doBindService", "Service is bound. bindService(...) Result: " + str);
    		}
    	};
    	t.start();
    }

    void doUnbindService() {
            unbindService(svcConnection);
    }
    
///*****************************************************************************************/
///*** private classes (AsyncTask usage)                                                 ***/
///*****************************************************************************************/
    
 
}
